package com.second.app.superthread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author GYZ
 * @Date 2024/1/22
 * <pre>
 *   验证屏障性以及getNumberWaiting方法的使用
 *   运行结果： 1 2 0 1 从运行结果来看确实有屏障重置性，也就是parties的值可以重置归为0；
 * </pre>
 */
public class CyclicBarrierValidPZ {

    public static void main(String[] args) {
        try {
            CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
            ThreadTO threadA1 = new ThreadTO(cyclicBarrier);
            threadA1.start();
            Thread.sleep(500);
            System.out.println(cyclicBarrier.getNumberWaiting());

            ThreadTO threadA2 = new ThreadTO(cyclicBarrier);
            threadA2.start();
            Thread.sleep(500);
            System.out.println(cyclicBarrier.getNumberWaiting());

            ThreadTO threadA3 = new ThreadTO(cyclicBarrier);
            threadA3.start();
            Thread.sleep(500);
            System.out.println(cyclicBarrier.getNumberWaiting());

            ThreadTO threadA4 = new ThreadTO(cyclicBarrier);
            threadA4.start();
            Thread.sleep(500);
            System.out.println(cyclicBarrier.getNumberWaiting());

        } catch (InterruptedException e) {
           e.printStackTrace();
        }

    }
}

class ThreadTO extends Thread{

    private final CyclicBarrier cbRef;

    public ThreadTO(CyclicBarrier cbRef){
        this.cbRef = cbRef;
    }

    @Override
    public void run() {
        try {
            cbRef.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    }
}
